<template>
  <div class="AllGoods">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item
              label="商品名称"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16, offset: 1 }"
            >
              <a-input
                placeholder="请输入"
                v-decorator="[
          'goodsName',
          {rules: [{ required: true, message: '请输入商品名称!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="商品代码" :label-col="{ span: 6}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input
                placeholder="请输入"
                v-decorator="[
          'goodsId',
          {rules: [{ required: true, message: '请输入商品ID!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="商品条码"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16, offset: 1}"
            >
              <a-input
                placeholder="请输入"
                v-decorator="[
          'goodsFridgecode',
          {rules: [{ required: true, message: '请输入商品条码!' }]}
        ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="商品分类" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1}">
              <a-select
                v-decorator="[
          'goodsClassify',
          {rules: [{ required: true, message: '请选择商品分类!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option :value="0">零食</a-select-option>
                <a-select-option :value="1">饮料</a-select-option>
                <a-select-option :value="2">标签</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="商品状态" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-select
                v-decorator="[
          'goodsStatus',
          {rules: [{ required: true, message: '请选择商品状态!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option :value="0">待上架</a-select-option>
                <a-select-option :value="1">正常</a-select-option>
                <a-select-option :value="2">已下架</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="创建时间" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-range-picker
                style="width: 100%"
                v-decorator="['creationTime',
          {rules: [{ required: true, message: '请选择创建时间!' }]}]"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="23" style="text-align:right;margin-left:30px;">
            <a-form-item>
              <a-button type="primary" @click="getfindPage()">查询</a-button>
              <a-button type="dashed" style="margin:0 10px" @click="listExport">导出</a-button>
              <a-button @click="handleReset()">重置</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top:2%">
      <router-link to="/home/goodsadmin/allgoods/goodsnew">
        <a-button type="primary" icon="plus">添加</a-button>
      </router-link>
      <a-table
        style="margin-top:2%"
        :columns="columns"
        :dataSource="data"
        @change="handleTableChange"
        :pagination="pagination"
        :rowKey="record => record.id"
      >
        <template slot="goodsImg" slot-scope="text,record">
          <img :src="record.imageUrl" alt="图片无法加载" style="width:100%">
        </template>
        <template slot="exhibitImg" slot-scope="text,record">
          <img :src="record.imageDisplayUrl" alt="图片无法加载" style="width:100%">
        </template>
        <template slot="isShelves" slot-scope="text,record">
          <span>{{record.isRemove==0?'已上架':'待上架'}}</span>
        </template>
        <template slot="operate" slot-scope="text,record">
          <div class="blue">
            <span @click="editInit(text.id)">编辑</span>
            <span
              @click="record.isRemove==0?outConfirm(text,record):showPutawayConfirm(text,record)"
            >{{record.isRemove==0?'下架':'上架'}}</span>
          </div>
          <div
            class="red"
            v-show="isLine"
            @click="record.isRemove==0?noDelete(text):showDeleteConfirm(text)"
          >删除</div>
          <a-modal
            title="编辑商品"
            :visible="visible"
            @ok="handleOk"
            @cancel="handleCancel"
            v-model="visible"
          >
            <template slot="footer">
              <a-button key="back" @click="handleCancel">取消</a-button>
              <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
            </template>
            <a-form-item
              label="商品名称"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16, offset: 1 }"
            >
              <a-input
                style="width: 100%"
                placeholder="请输入"
                v-decorator="[
          'goodsName',
          {rules: [{ required: true, message: '请输入姓名!' }]} 
        ]"
              />
            </a-form-item>
            <a-form-item
              label="商品分类"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16, offset: 1 }"
            >
              <a-select
                style="width: 100%"
                v-decorator="[
          'goodsClassify',
          {rules: [{ required: true, message: '请选择商品分类!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option value="snacks">零食</a-select-option>
                <a-select-option value="drinks">饮料</a-select-option>
                <a-select-option value="tag">标签</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="算法识别码"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16, offset: 1 }"
            >
              <a-select
                style="width: 100%"
                v-decorator="[
          'arithDiscern',
          {rules: [{ required: true, message: '请选择算法识别码!' }]}
        ]"
                placeholder="全部"
              >
                <a-select-option value="1">算法001</a-select-option>
                <a-select-option value="2">算法002</a-select-option>
                <a-select-option value="3">算法003</a-select-option>
                <a-select-option value="4">算法004</a-select-option>
              </a-select>
            </a-form-item>
          </a-modal>
        </template>
      </a-table>
      <!-- <div
        class="count"
      >共{{pagination.total}}条 第{{pagination.current}}/{{pagination.total/pagination.pageSize}}页</div>-->
    </a-card>
  </div>
</template>

<script>
import moment from "moment";
const columns = [
  {
    title: "商品代码",
    dataIndex: "catId",
    key: "goodsID",
    scopedSlots: { customRender: "goodsID" },
    align: "center"
  },
  {
    title: "商品名称",
    dataIndex: "name",
    key: "goodsName",
    scopedSlots: { customRender: "goodsName" },
    align: "center"
  },
  {
    title: "自定义商品编码",
    dataIndex: "customCode",
    key: "customGoodsCode",
    scopedSlots: { customRender: "customGoodsCode" },
    align: "center"
  },
  {
    title: "商品图",
    dataIndex: "imageUrl",
    key: "goodsImg",
    scopedSlots: { customRender: "goodsImg" },
    align: "center",
    width: "10%"
  },
  {
    title: "占用列",
    key: "colspann",
    dataIndex: "occupancyColumn",
    scopedSlots: { customRender: "colspann" },
    align: "center"
  },
  {
    title: "货道可放置数",
    key: "aisleNum",
    dataIndex: "placementNumber",
    scopedSlots: { customRender: "aisleNum" },
    align: "center"
  },
  {
    title: "商品陈列图",
    dataIndex: "imageDisplayUrl",
    key: "exhibitImg",
    scopedSlots: { customRender: "exhibitImg" },
    align: "center",
    width: "10%"
  },
  {
    title: "商品条码",
    dataIndex: "barCode",
    key: "goodsFridgecode",
    scopedSlots: { customRender: "goodsFridgecode" },
    align: "center"
  },
  {
    title: "商品分类",
    dataIndex: "categoryName",
    key: "goodsCategory",
    scopedSlots: { customRender: "goodsCategory" },
    align: "center"
  },
  {
    title: "上架状态",
    dataIndex: "isRemove",
    key: "isShelves",
    scopedSlots: { customRender: "isShelves" },
    align: "center"
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "creationTime",
    scopedSlots: { customRender: "creationTime" },
    align: "center"
  },
  {
    title: "操作",
    key: "operate",
    dataIndex: "",
    scopedSlots: { customRender: "operate" },
    align: "center",
    width: "9%"
  }
];
export default {
  name: "AllGoods",
  data() {
    return {
      form: this.$form.createForm(this),
      data: [],
      columns,
      visible: false,
      isLine: true,
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["2", "4", "8", "10", "12"],
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        },
        pageSize: 8, //每页条数
        defaultCurrent: 1, //默认当前页
        current: 1, //当前页
        total: 500 //数据总条数
      }
    };
  },
  watch: {},
  methods: {
    handleReset() {
      this.form.resetFields();
    },
    handleMenuClick(e) {
      console.log("click", e);
    },
    moment,
    onChange(dates, dateStrings) {
      console.log("From: ", dates[0], ", to: ", dates[1]);
      console.log("From: ", dateStrings[0], ", to: ", dateStrings[1]);
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;
      this.getfindPage();
    },
    handleOk(e) {
      this.visible = false;
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
    noDelete(text, record) {
      this.$message.error("下架后的商品才能删除");
    },
    // 删除确认弹框
    showDeleteConfirm(text) {
      var that = this;
      this.delId = text.id;
      this.$confirm({
        title: "确认要删除此商品？",
        content: "删除后，再次售卖该商品需要重新学习和添加。",
        okText: "确定",
        cancelText: "取消",
        iconType: "close-circle",
        onOk() {
          that.del(that.delId);
          console.log("OK");
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    },
    // 上架方法
    showPutawayConfirm(text, record) {
      var that = this;
      this.putawayId = record.id;
      this.$confirm({
        title: "确认要上架该商品吗？",
        content: "确认设备学习过该商品,可以被设备识别.否则会生成异常订单.",
        okText: "确定",
        cancelText: "取消",
        iconType: "exclamation-circle",
        onOk() {
          console.log("OK");
          that.onGoods();
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    },
    // 下架方法
    outConfirm(text, record) {
      var that = this;
      this.outId = record.id;
      this.$confirm({
        title: `确认要下架该商品吗？`,
        content: "下架该商品之后，代理商下次上货的时候不能售卖该商品。",
        okText: "确定",
        cancelText: "取消",
        iconType: "exclamation-circle",
        onOk() {
          console.log("OK");
          that.outGoods();
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    },
    // 列表初始化
    listInit() {
      this.axios
        .post(this.baseUrl + "/goods/listInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 查询商品列表
    getfindPage() {
      var values = this.form.getFieldsValue();
      if (values.creationTime == undefined) {
        values.creationTime == undefined;
      } else {
        this.startCreateTime = moment(values.creationTime[0]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endCreateTime = moment(values.creationTime[1]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.axios
        .post(this.baseUrl + "/goods/findPageListByCondition", {
          loginToken: this.$store.state.loginToken,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          barCode: values.goodsFridgecode,
          catId: values.goodsClassify,
          code: values.goodsId,
          startCreateTime: this.startCreateTime,
          endCreateTime: this.endCreateTime,
          isRemove: values.goodsStatus,
          name: values.goodsName
        })
        .then(response => {
          // console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 编辑商品初始化
    editInit(id) {
      var editId = id;
      this.$store.commit("editId", editId);
      this.$router.push({
        path: "/home/goodsadmin/allgoods/allgoodsedit"
      });
    },
    // 上架商品
    onGoods() {
      this.axios
        .post(this.baseUrl + "/goods/onGoods", {
          loginToken: this.$store.state.loginToken,
          id: this.putawayId,
          isRemove: 0
        })
        .then(response => {
          // console.log(response);
          if (response.data.code == 0) {
            this.$message.info("上架成功");
            this.getfindPage();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    // 下架商品
    outGoods() {
      this.axios
        .post(this.baseUrl + "/goods/onGoods", {
          loginToken: this.$store.state.loginToken,
          id: this.outId,
          isRemove: 1
        })
        .then(response => {
          // console.log(response);
          if (response.data.code == 0) {
            this.$message.info("下架成功");
            this.getfindPage();
          }
          if (response.data.code == -1) {
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 删除商品
    del(id) {
      this.axios
        .post(this.baseUrl + "/goods/del", {
          id: id,
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          this.getfindPage();
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 导出商品列表
    listExport() {
      var values = this.form.getFieldsValue();
      if (values.creationTime == undefined) {
        values.creationTime == undefined;
      } else {
        this.startCreateTime = moment(values.creationTime[0]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endCreateTime = moment(values.creationTime[1]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.axios
        .post(
          this.baseUrl + "/goods/export",
          {
            barCode: values.goodsFridgecode,
            catId: values.goodsClassify,
            code: values.goodsId,
            startCreateTime: this.startCreateTime,
            endCreateTime: this.endCreateTime,
            isRemove: values.goodsStatus,
            name: values.goodsName,
            loginToken: this.$store.state.loginToken
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "总商品库表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        })
        .catch(error => {
          // console.log(error);
        });
    }
  },
  created() {
    this.listInit();
    this.getfindPage();
  },
  mounted() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.AllGoods {
  width: 100%;
}
</style>
